<?php
defined('IN_IA') or exit('Access Denied');

$table_subject = 'hellozjx_mapwxapp_subject';
global $_W, $_GPC;
load()->func('tpl');
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
if ($operation == 'display') {
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $list = pdo_fetchall("SELECT name,sort,id,status FROM " . tablename($table_subject) . " WHERE status between 1 and 2 ORDER BY sort DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
    $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($table_subject) . " WHERE status between 1 and 2");
    $pager = pagination($total, $pindex, $psize);
} elseif ($operation == 'post') {
    $id = intval($_GPC['id']);
    if (checksubmit('submit')) {
        $where = '';

        if(!empty($id))
            $where = " AND id<>{$id}";
        $isExists = pdo_fetch("select id from " .tablename($table_subject)." where name='{$_GPC['name']}' and status<>0 {$where}" );
        if($isExists)   //判断科目名称是否已经存在
            message('科目名称已存在，不可重复添加！', $this->createWebUrl('subject', array('op' => 'display')), 'error');

        $data = array( 'name' => $_GPC['name'], 'status' => intval($_GPC['status']), 'sort' => intval($_GPC['sort']), 'create_time' => date('Y-m-d H:i:s',time()));
        if (!empty($id)) {
            unset($data['create_time']);
            pdo_update($table_subject, $data, array('id' => $id));
        } else {
            pdo_insert($table_subject, $data);
            $id = pdo_insertid();
        }
        message('更新分类成功！', $this->createWebUrl('subject', array('op' => 'display')), 'success');
    }
    $subject = pdo_fetch("select * from " . tablename($table_subject) . " where id=:id limit 1", array(":id" => $id));
    if (empty($subject)) {
        $subject['sort'] = 0;
        $subject['status'] = 1;
    }
} elseif ($operation == 'delete') {
    $id = intval($_GPC['id']);
    $subject = pdo_fetch("SELECT id FROM " . tablename($table_subject) . " WHERE id = '{$id}' and status=0");
    if (!empty($subject)) {
        message('抱歉，科目不存在或是已经被删除！', $this->createWebUrl('subject', array('op' => 'display')), 'error');
    }
    pdo_update($table_subject, ['status'=>0],['id' => $id]);
    message('删除成功', referer(), 'success');
}
include $this->template('subject');